﻿using Domain.IRepositorys;
using Domain.Types;
using Infrastructure.AggregateBase;
using Infrastructure.Cache;
using Infrastructure.Error;
using Infrastructure.Http;
using Infrastructure.UniOfWorkBase;
using OtherLib.TenXun;
using System;
using Utility;

namespace Domain.Services
{
    public class SmsService : IService
    {
        public IEFUnitOfWork EFUnitOfWork { get; set; }
        public ISmsCodeRepository smsCodeRepository { get; set; }
        public IMemoryCacheService memoryCacheService { get; set; }
        public IHttpService httpService { get; set; }
        public bool SendSms(string phone, SmsCodeType smsCodeType, string ip)
        {
            var key = $"SmsService.SendSms.Hour.{phone}.{(int)smsCodeType}";
            var lastTimeKey = $"SmsService.SendSmsTime.Hour.{phone}.{(int)smsCodeType}";

            var hourSendLastTime = memoryCacheService.Get<DateTime?>(lastTimeKey);
            if (hourSendLastTime != null && DateTime.Now < hourSendLastTime)
            {
                throw new BizException("验证码发送频率过高,请稍后再试!");
            }

            var hourSendTime = memoryCacheService.Get<int>(key);

            if (hourSendTime > 5)
            {
                throw new BizException("验证码发送频率过高,请稍后再试!");
            }

            //发送短信
            SmsCodeAggregate smsCodeAggregate = new SmsCodeAggregate();

            smsCodeAggregate.OutTime = DateTime.Now.AddMinutes(20);
            smsCodeAggregate.SmsCodeType = smsCodeType;
            smsCodeAggregate.Phone = phone;
            smsCodeAggregate.SmsCode = RandomUtil.GetRandomNum(4);



            if (hourSendTime == 0)
            {
                memoryCacheService.Set(key, ++hourSendTime, TimeSpan.FromHours(1));
                memoryCacheService.Set(lastTimeKey, DateTime.Now.AddSeconds(30), TimeSpan.FromHours(1));
            }
            else hourSendTime++;

            try
            {
                //SmsUtils.Send(phone, $"{{\"code\":\"{ smsCodeAggregate.SmsCode}\"}}");

                SendSmsUtil.SendSms(phone, smsCodeAggregate.SmsCode);
                smsCodeAggregate.SendSuccess = true;
                smsCodeAggregate.SendMsg = "发送成功";
            }
            catch (BizException ex)
            {
                smsCodeAggregate.SendSuccess = false;
                smsCodeAggregate.SendMsg = ex.Message;

                throw new BizException($"验证码发送失败,{ ex.Message}!");
            }
            smsCodeRepository.Insert(smsCodeAggregate);

            EFUnitOfWork.Commit();

            return true;
        }
    }
}
